package com.ruoyi.project.purchase.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.ResultBean;
import com.ruoyi.project.purchase.domain.RyDepotDetail;
import com.ruoyi.project.purchase.domain.RyDepotHead;
import com.ruoyi.project.purchase.domain.pojo.DepotDetailBean;
import com.ruoyi.project.purchase.domain.pojo.DepotHeadItem;
import com.ruoyi.project.purchase.domain.pojo.InventoryBean;
import com.ruoyi.project.purchase.service.IRyDepotHeadService;
import com.ruoyi.project.warehouse.domain.RyDepotItem;
import com.ruoyi.project.warehouse.domain.RyInventoryCurrentStock;
import com.ruoyi.project.warehouse.domain.WareCurrentStock;
import com.ruoyi.project.warehouse.service.IRyDepotItemService;
import com.ruoyi.project.warehouse.service.IWareCurrentStockService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.purchase.domain.RyPurchaseOrder;
import com.ruoyi.project.purchase.service.IRyPurchaseOrderService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 采购订单Controller
 *
 * @author you
 * @date 2022-10-11
 */
@RestController
@RequestMapping("/purchase/purchaseOrder")
public class RyPurchaseOrderController extends BaseController
{
    @Autowired
    private IRyPurchaseOrderService ryPurchaseOrderService;

    @Autowired
    private IRyDepotHeadService ryDepotHeadService;

    @Autowired
    private IWareCurrentStockService wareCurrentStockService;

    @Autowired
    private IRyDepotItemService ryDepotItemService;


    /**
     * 查询采购订单列表
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(RyPurchaseOrder ryPurchaseOrder)
    {
        startPage();
        ryPurchaseOrder.setType("其他");
        ryPurchaseOrder.setSubType("采购订单");
        List<RyPurchaseOrder> list = ryPurchaseOrderService.selectRyPurchaseOrderList(ryPurchaseOrder);
        return getDataTable(list);
    }

    /**
     * 查询所有可用项目总清单
     */
    @GetMapping("/allList")
    public AjaxResult allList()
    {
        RyPurchaseOrder ryPurchaseOrder = new RyPurchaseOrder();
        ryPurchaseOrder.setType("其他");
        ryPurchaseOrder.setSubType("采购订单");
        List<RyPurchaseOrder> list = ryPurchaseOrderService.selectRyPurchaseOrderList(ryPurchaseOrder);
        return AjaxResult.success(list);
    }

    /**
     * --采购订单
     * 新增采购订单及采购订单子表信息
     * @return
     * @throws Exception
     */
    @RequestMapping("/addDepotHeadAndDetail")
    public AjaxResult addDepotHeadAndDetail(@RequestBody DepotHeadItem depotHeadItem)
    {
//        System.out.println("depotHeadItem---->" + depotHeadItem);
        System.out.println("linkHeadId---->" + depotHeadItem.getLinkHeadId());
        return ryPurchaseOrderService.addDepotHeadAndDetail(depotHeadItem);
    }


    /**
     * --采购订单
     * 修改购订单及采购订单子表信息
     */
    @RequestMapping("/editDepotHeadAndDetail")
    public AjaxResult editDepotHeadAndDetail(@RequestBody DepotHeadItem depotHeadItem)
    {
        System.out.println("depotHeadItem---->" + depotHeadItem);
        return ryPurchaseOrderService.editDepotHeadAndDetail(depotHeadItem);
    }


    /**
     * --采购订单
     * 获取采购订单主表及子表详细信息
     */
    @GetMapping(value = "/selectRyDepotDetailById/{id}")
    public AjaxResult selectRyDepotDetailById(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ryPurchaseOrderService.selectRyDepotDetailById(id));
    }

    /**
     * --采购订单
     * 获取所有可关联采购订单信息（采购质检使用）
     * 首先查询出质检单关联的采购订单id,这些采购订单id排除后的采购订单才是可用的
     *
     */
    @GetMapping("/allForQuality")
    public AjaxResult allForQuality(){
        //首先查询出所有质检单
        RyDepotHead ryDepotHead = new RyDepotHead();
        ryDepotHead.setType("其他");
        ryDepotHead.setSubType("采购质检");
        List<RyDepotHead> list = ryDepotHeadService.selectRyDepotHeadList(ryDepotHead);
        //需要排除的id列表
        List<Long> paramList =  new ArrayList<Long>();
        //质检单数据不存在，查询所有
        if(list.size() <= 0 || list == null){
            paramList = null;
        } else {
            //遍历结果，筛选出关联的采购订单id
            for(RyDepotHead ryDepotHead1 : list){
                if(ryDepotHead1.getLinkHeadId() != null){
                    paramList.add(ryDepotHead1.getLinkHeadId());
                }
            }
            //如果没有id需要排除则赋值为null,否则数据库会报错
            if(paramList.size() <= 0){
                paramList = null;
            }
        }
        //根据条件筛选可关联的采购订单
        List<RyPurchaseOrder> resList = ryPurchaseOrderService.allUsed(paramList);
        return AjaxResult.success(resList);
    }


    /**
     * --采购订单
     * 获取所有可关联采购订单信息（采购入库使用）
     * 首先查询出采购入库单关联的采购订单id,这些采购订单id排除后的采购订单才是可用的
     *
     */
    @GetMapping("/allForPurchaseIn")
    public AjaxResult allForPurchaseIn(){
        //首先查询出所有采购入库单
        RyDepotHead ryDepotHead = new RyDepotHead();
        ryDepotHead.setType("入库");
        ryDepotHead.setSubType("采购");
        List<RyDepotHead> list = ryDepotHeadService.selectRyDepotHeadList(ryDepotHead);
        //需要排除的id列表
        List<Long> paramList =  new ArrayList<Long>();
        //采购单数据不存在，查询所有
        if(list.size() <= 0 || list == null){
            paramList = null;
        } else {
            //遍历结果，筛选出关联的采购订单id
            for(RyDepotHead ryDepotHead1 : list){
                if(ryDepotHead1.getLinkHeadId() != null){
                    paramList.add(ryDepotHead1.getLinkHeadId());
                }
            }
            //如果没有id需要排除则赋值为null,否则数据库会报错
            if(paramList.size() <= 0){
                paramList = null;
            }
        }
        //根据条件筛选可关联的采购订单
        List<RyPurchaseOrder> resList = ryPurchaseOrderService.allUsed(paramList);
        return AjaxResult.success(resList);
    }


    /**
     * 新增明细数据时
     * 查询物品关联信息
     */
    @RequestMapping("/getInfoByInventory")
    public AjaxResult getInfoByInventory(@RequestBody InventoryBean inventoryBean){
        System.out.println("inventoryBean---->" + inventoryBean);
        //采购总清单明细表
        RyDepotDetail ryDepotDetail = new RyDepotDetail();
        ryDepotDetail.setSupply(inventoryBean.getSupply());//供应商
        ryDepotDetail.setAdvancePurchaseNum(Double.valueOf(0));//待采购数量
        ryDepotDetail.setInventoryId(inventoryBean.getId());//物品id
        ryDepotDetail.setInventoryName(inventoryBean.getName());//物品名称
        ryDepotDetail.setInventorySpecifications(inventoryBean.getSpecifications());//物品规格
        ryDepotDetail.setWbs(inventoryBean.getWbs());//wbs编码
        ryDepotDetail.setUnitPrice(inventoryBean.getUnitPrice());
        ryDepotDetail.setBrand(inventoryBean.getBrand()); // 品牌

        //根据物品id和总仓库id查询总库库物品当前库存量以及相关信息(总库id为1)
        RyInventoryCurrentStock ryInventoryCurrentStock = new RyInventoryCurrentStock();
        ryInventoryCurrentStock.setInventoryId(inventoryBean.getId());//物品id
        ryInventoryCurrentStock.setDepotId(1L);//仓库id
        WareCurrentStock wareCurrentStock = wareCurrentStockService.getInfoByDepotInventoryId(ryInventoryCurrentStock);
        if(wareCurrentStock == null){
            ryDepotDetail.setUsableNum(Double.valueOf(0));//总库可用数量
        } else {
            //如果不为空则判断是否存在锁定数量
            RyDepotItem param = new RyDepotItem();
            param.setInventoryId(inventoryBean.getId());
            param.setDepotId(1L);
            RyDepotItem result = ryDepotItemService.getLockNumById(param);
            if(result != null){//不为空，存在锁定数量
                ryDepotDetail.setUsableNum(wareCurrentStock.getCurrentNumber() - result.getOperNumber());//总库可用数量 - 锁定
            } else {
                ryDepotDetail.setUsableNum(wareCurrentStock.getCurrentNumber());//总库可用数量
            }

        }

        //成功返回
        return AjaxResult.success(ryDepotDetail);
    }

    /**
     * 获取采购订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ryPurchaseOrderService.selectRyPurchaseOrderById(id));
    }


    /**
     * 导出采购订单列表
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:export')")
    @Log(title = "采购订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RyPurchaseOrder ryPurchaseOrder)
    {
        List<RyPurchaseOrder> list = ryPurchaseOrderService.selectRyPurchaseOrderList(ryPurchaseOrder);
        ExcelUtil<RyPurchaseOrder> util = new ExcelUtil<RyPurchaseOrder>(RyPurchaseOrder.class);
        util.exportExcel(response, list, "采购订单数据");
    }


    /**
     * 新增采购订单
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:add')")
    @Log(title = "采购订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RyPurchaseOrder ryPurchaseOrder)
    {
        return toAjax(ryPurchaseOrderService.insertRyPurchaseOrder(ryPurchaseOrder));
    }

    /**
     * 修改采购订单
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:edit')")
    @Log(title = "采购订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RyPurchaseOrder ryPurchaseOrder)
    {
        return toAjax(ryPurchaseOrderService.updateRyPurchaseOrder(ryPurchaseOrder));
    }

    /**
     * 删除采购订单
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchaseOrder:remove')")
    @Log(title = "采购订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ryPurchaseOrderService.deleteRyPurchaseOrderByIds(ids));
    }
}
